<template>
  <div class="app-container">
    <div class="filter-container" style="display: flex;align-items: center;justify-content: space-between;">
      <el-button
        size="mini"
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        新增专栏
      </el-button>
      <div>
        <el-select
          v-model="listQuery.status"
          size="mini"
          style="width: 140px;margin-right: 10px;"
          class="filter-item"
          @change="handleFilter"
        >
          <el-option v-for="(item,k) in statusOptions" :key="k" :label="item" :value="k">
            <span style="float: left">{{ item }}</span>
          </el-option>
        </el-select>
        <el-input
          v-model="listQuery.title"
          size="mini"
          placeholder="标题"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="handleFilter"
        />
        <el-button v-waves size="mini" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
          搜索
        </el-button>
      </div>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column
        label="ID"
        prop="id"
        sortable="custom"
        align="center"
        width="80"
        :class-name="getSortClass('id')"
      >
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column label="课程描述" min-width="150px">
        <template slot-scope="{row}">
          <div style="display: flex;">
            <img style="width: 100px;height:50px;" :src="row.cover" alt="">
            <div style="display: flex;flex-direction: column;margin-left: 10px;">
              <span>{{ row.title }}</span>
              <span style="color: red;">￥{{ row.price }}</span>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="连载"
        prop="id"
        sortable="custom"
        align="center"
        width="80"
        :class-name="getSortClass('id')"
      >
        <template slot-scope="{row}">
          <span :style="row.isend?'color:black;':'color:red;'">{{ row.isend?'已完结':'连载中...' }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="订阅量"
        prop="id"
        sortable="custom"
        align="center"
        width="80"
        :class-name="getSortClass('id')"
      >
        <template slot-scope="{row}">
          <span>{{ row.sub_count }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.created_time }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" class-name="status-col" width="100">
        <template slot-scope="{row}">
          <el-tag :type="row.status===0?'danger':'success'">
            {{ row.status | statusFilter }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="Actions" align="center" width="300" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="warning" size="mini" @click="openDetail(row)">
            专栏
          </el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status==1" size="mini" @click="handleModifyStatus(row,0)">
            下架
          </el-button>
          <el-button v-if="row.status==0" type="success" size="mini" @click="handleModifyStatus(row,1)">
            上架
          </el-button>
          <el-popconfirm style="margin-left: 10px;" title="是否要删除该记录" @onConfirm="handleDelete(row,$index)">
            <el-button v-if="row.status!='deleted'" slot="reference" size="mini" type="danger">
              删除
            </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" fullscreen :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="70px"
        style="width: 400px; margin-left:50px;"
      >

        <el-form-item label="标题" prop="title">
          <el-input v-model="temp.title" />
        </el-form-item>
        <el-form-item label="课程描述" prop="try">
          <el-input
            v-model="temp.try"
            type="textarea"
            :rows="2"
            placeholder="课程描述"
          />
        </el-form-item>
        <el-form-item label="课程内容" prop="content">
          <tinymce v-model="temp.content" style="width: 600px;" :height="300" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="temp.status">
            <el-radio :label="0">上架</el-radio>
            <el-radio :label="1">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="更新状态" prop="isend">
          <el-radio-group v-model="temp.isend">
            <el-radio :label="0">连载中...</el-radio>
            <el-radio :label="1">已完结</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="temp.price" :min="0" label="请输入价格" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          返回
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import waves from '@/directive/waves' // waves directive
import Tinymce from '@/components/Tinymce'
import {
  fetchList,
  createColumn,
  updateColumn
} from '@/api/column'

import Pagination from '@/components/Pagination' // secondary package based on el-pagination

const statusOptions = {
  0: '已下架',
  1: '已上架'
}

export default {
  name: 'ComplexTable',
  components: {
    Pagination,
    Tinymce
  },
  directives: {
    waves
  },
  filters: {
    statusFilter(status) {
      return statusOptions[status]
    }

  },
  data() {
    return {
      fileList: [{
        name: 'food.MP4',
        url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
      }],
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        status: undefined,
        title: undefined,
        sort: '+id'
      },
      importanceOptions: [1, 2, 3],
      statusOptions,
      sortOptions: [{
        label: 'ID Ascending',
        key: '+id'
      }, {
        label: 'ID Descending',
        key: '-id'
      }],
      showReviewer: false,
      temp: {
        id: undefined,
        title: undefined,
        cover: undefined,
        try: undefined,
        conent: undefined,
        price: undefined,
        status: 1,
        isend: 0
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '创建'
      },

      rules: {
        title: [{
          required: true,
          message: '标题不能为空',
          trigger: 'blur'
        }],
        cover: [{
          required: true,
          message: '文章封面不能为空',
          trigger: 'blur'
        }],
        try: [{
          required: true,
          message: '文章试看不能为空',
          trigger: 'blur'
        }],
        content: [{
          required: true,
          message: '文章内容不能为空',
          trigger: 'blur'
        }],
        price: [{
          required: true,
          message: '文章价格不能为空',
          trigger: 'blur'
        }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    onChange(fileList) {
      this.temp.cover = fetchList[0].url
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(file)
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    getList() {
      this.listLoading = true
      console.log(this.listQuery)
      fetchList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.listQuery.status = parseInt(this.listQuery.status)
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const {
        prop,
        order
      } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        title: undefined,
        cover: undefined,
        try: undefined,
        conent: undefined,
        price: undefined,
        status: 1,
        isend: 0
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          createColumn(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData
            .timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateColumn(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$notify({
        title: '成功提示',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    openDetail(row) {
      console.log(row)
      this.$router.push({ name: 'CloumnDetail', query: { id: row.id }})
    }

  }
}

</script>
